package mgotool

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"local.public/innerpkg/logger"
	"log"
)

var dbMongoClient *mongo.Client

type MgWorkerOrder struct {
	WoId   string `json:"WoId"`
	WoNum  string `json:"WoNum"`
	WoType string `json:"WoType"`
}

func InitMongoDb(dsn string) error {
	clientOptions := options.Client().ApplyURI(dsn)
	// mongodb://root:****@dds-bp*******1.mongodb.rds.aliyuncs.com:3717,dds-bp*******2.mongodb.rds.aliyuncs.com:3717/admin?replicaSet=mgset-XXXXX
	// 连接到MongoDB
	// 与mongo.NewClient()等价
	client, err := mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		log.Fatal(err)
		return err
	}
	// 检查连接
	err = client.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatal(err)
		return err
	}
	dbMongoClient = client
	fmt.Println("Connected to MongoDB!")
	return nil
}

func InsertOneWithJsonString(databaseName, collectionName, sJson string) error {
	collection := dbMongoClient.Database(databaseName).Collection(collectionName)

	doc := bson.D{}

	if err3 := bson.UnmarshalExtJSON([]byte(sJson), true, &doc); err3 != nil {
		logger.Error(err3)
	}

	_, err := collection.InsertOne(context.Background(), doc)

	if err != nil {
		return err
	}
	logger.Debug("Mongodb insert one json ok.")
	return nil
}

func InsertOneStruct(databaseName string, collectionName string, doc interface{}) error {
	collection := dbMongoClient.Database(databaseName).Collection(collectionName)

	_, err := collection.InsertOne(context.Background(), doc)

	if err != nil {
		return err
	}
	logger.Debug("Mongodb insert one stu ok.")
	return nil
}

func FindOkWithWoId(databaseName string, collectionName string, woId string) (findOk bool) {
	//logger.Debug("查 %s in collection: %s", woId, collectionName)
	collection := dbMongoClient.Database(databaseName).Collection(collectionName)
	filter := bson.M{
		"WoId": woId,
		//"WoId": "609410db-dbcf-ef11-80d5-0050569acfff",
	}
	var wo MgWorkerOrder
	result1 := collection.FindOne(context.Background(), filter)
	//s, _ := result1.Raw()
	//logger.Debug("Raw记录: %s", s)
	err2 := result1.Decode(&wo)
	if err2 != nil {
		logger.Debug("查 %s in %s,decode失败!", woId, collectionName)
		return false
	}
	logger.Debug("查 %s in %s,decode成功!", woId, collectionName)
	logger.Debug(wo)

	return true
}

func FindOneWithWoId(databaseName string, collectionName string, woId string) (res *mongo.SingleResult, findOk bool) {
	//logger.Debug("查 %s in collection: %s", woId, collectionName)
	collection := dbMongoClient.Database(databaseName).Collection(collectionName)
	filter := bson.M{
		"WoId": woId,
		//"WoId": "609410db-dbcf-ef11-80d5-0050569acfff",
	}
	var wo MgWorkerOrder
	result1 := collection.FindOne(context.Background(), filter)
	//s, _ := result1.Raw()
	//logger.Debug("Raw记录: %s", s)
	err2 := result1.Decode(&wo)
	if err2 != nil {
		logger.Debug("查 %s in %s,decode失败!", woId, collectionName)
		return nil, false
	}
	logger.Debug("查 %s in %s,decode成功!", woId, collectionName)

	return result1, true
}
func CloseMongoDb() {
	err := dbMongoClient.Disconnect(context.TODO())
	if err != nil {
		log.Fatal(err)
	}

	logger.Debug("Connection to MongoDB closed.")
}
